package com.stefan.framework.protocol.http;

import com.stefan.framework.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

//用来发送HTTP请求的客户端类
public class HttpClient {
    public String send(String hostname, int port, Invocation invocation)  {
        // 这里可以使用HttpURLConnection或其他HTTP客户端库来发送请求
        // 例如，使用HttpURLConnection发送POST请求
        // 这里只是一个示例，实际实现需要处理异常和响应等
        //这里帮我换一种写法

        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL("http", hostname, port, "/");
            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);

            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            String result = IOUtils.toString(inputStream);
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
